var http = require('http');
var fs = require('fs');
var url = require('url');
var util = require('util');
var path = require('path');

http.createServer(function(req,res){
    var filepath = decodeURI(url.parse(req.url).pathname);
    console.log('Request Url: ',filepath);
    if(filepath.indexOf('/getlist') != -1){
        console.log('start api mode.');
        res.writeHead(200,{'Content-Type':'application/json; charset=utf-8'});
        fs.readdir('./musics',function(err,files){
            var musics = [];
            files.forEach(function(val,index){
                if (path.extname(val) == '.mp3' /*|| path.extname(val) == '.flac'*/){
                    var music = {};
                    music['name'] = path.parse(val).name;
                    music['url'] =  path.parse(val).base;
                    musics.push(music);
                    
                }
            })
            res.write(JSON.stringify(musics));
            res.end();
            console.log('Send Music Json');
        })
    }else{
        var ext = path.extname(filepath);
        if(ext == '.mp3' || ext == '.flac'){
            console.log('Sending music.');
            //console.log('Music: '+decodeURI((filepath).pathname.substring(1)))
            fs.readFile('./musics/'+decodeURI((filepath).substring(1)),function(err,data){
                if (err){
                    return console.error(err);
                }
                var ctt = 'audio/'+ext.replace('.','')+'; charset=utf-8';
                res.writeHead(200,{'Content-Type':ctt});
                res.write(data);
                res.end();
            })
        }else{
            console.log('Request ext now:',path.extname(filepath))
            console.log('No send music.');
            res.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});
            res.write('Plaese request music file!!!\n');
            res.write("<html><head><meta charset='utf-8'></head><body><ul>");
            fs.readdir('./musics',function(err,files){
                files.forEach(function(val,index){
                    if (path.extname(val) == '.mp3' || path.extname(val) == '.flac')
                    res.write('<li><a href="/'+path.parse(val).base+'">'+path.parse(val).name+'</a></li>');
                })
                res.write("</ul></body></html>");
                res.end();
            })
        }
    }
    
    
}).listen(2000,function(){
    console.log('Server listening at:',2000);
});